package com.runchamp;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.SystemClock;
import android.speech.tts.TextToSpeech;
import android.view.ContextThemeWrapper;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.runchamp.locationUtils.RunLocationManager;
import com.runchamp.locationUtils.TripStatistics;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;


/*
    This Activity handles the Live Race session, including sending the server updates about the
     client's location, and receiving updates about all of the other participants progress.
 */
public class LiveRace extends Activity implements AdapterView.OnItemClickListener {
    private static final String SERVER_URL = "http://runtobo.appspot.com/liverace/updatestats";
    private static final String SERVER_URL_USER_STATUS = "http://runtobo.appspot.com/liverace/updateuserstatus";
    private static final String SERVER_URL_RACE_STATUS = "http://runtobo.appspot.com/liverace/updateracestatus";
    private static final String SERVER_URL_CREATESTATS = "http://runtobo.appspot.com/currentStats";
    final Float KM = 3.6f;
    protected JSONAdapterStatsList mJSONAdapter;
    LocationManager locationManager;
    TextView speedTextView;
    TextView avgSpeedTextView;
    TextView distanceTextView;
    TextView calorieTextView;
    TextView distanceFromWinnerTextView;
    TextView positionTextView;
    TextView numOfParticipants;
    RelativeLayout progressLayout;
    TextToSpeech tts;
    CountDownTimer countDownTimer;
    AlertDialog alertDialog;
    long elapsedMillis;
    int timeCnt = 1;
    int distanceCnt = 1;
    boolean multiUserMode = false;
    CurrentStats myStats;
    AsyncHttpClient client;
    RequestParams params;
    RequestParams params2;
    UpdateRunnable updateChecker;
    Intent finishedIntent;
    ListView racesListView;
    MediaPlayer SoundRaceStarts;
    MediaPlayer SoundYouPassed;
    MediaPlayer SoundSomeOnePassedYou;
    private Chronometer chronometer;
    private int getUpdatesInterval = 1000; // 1 second
    private Handler raceUpdateHandler;
    private RunLocationManager runLocationManager;
    private LocationListener locationListener;
    private int currentTab = 0;
    private int NUM_OF_PARTICIPANTS = 1;
    private double RACE_DISTANCE;
    private int myPosition = 0;
    private int myRealPos = 0;
    private int myPrevPsotion = 0;
    private double distanceFromWinner = 0;
    private Bundle race;
    private int raceStarted = 0;
    private Double distanceFreq;
    private Double timeFreq;
    private int informationIndex;
    private boolean alertsOnTouch;
    private UpdateStatsResponseHandler updateStatsResponseHandler;
    private Button giveUpButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        updateStatsResponseHandler = new UpdateStatsResponseHandler();
        race = this.getIntent().getExtras();
        runLocationManager = new RunLocationManager();
        setContentView(R.layout.activity_live_race);
        speedTextView = (TextView) findViewById(R.id.speed_value);
        avgSpeedTextView = (TextView) findViewById(R.id.avg_speed_value);
        distanceTextView = (TextView) findViewById(R.id.distance_value);
        chronometer = (Chronometer) findViewById(R.id.chronometer);
        calorieTextView = (TextView) findViewById(R.id.calorie_value);
        distanceFromWinnerTextView = (TextView) findViewById(R.id.distance_behind_winner_value);
        positionTextView = (TextView) findViewById(R.id.position_value);
        numOfParticipants = (TextView) findViewById(R.id.num_of_participants);
        NUM_OF_PARTICIPANTS = Integer.parseInt(race.getString("numofparticipants"));
        numOfParticipants.setText("/" + String.valueOf(NUM_OF_PARTICIPANTS));
        progressLayout = (RelativeLayout) findViewById(R.id.progress);
        giveUpButton = (Button) findViewById(R.id.exit);
        giveUpButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                giveUp(giveUpButton);
            }
        });
        client = new AsyncHttpClient();
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);


        if (NUM_OF_PARTICIPANTS > 1) {
            multiUserMode = true;
        }

        alertDialog = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.Theme_AppCompat_Dialog)).create();
        alertDialog.setTitle("Race starting in 10 seconds");
        alertDialog.setMessage("Good luck");
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.show();   //


        SoundRaceStarts = MediaPlayer.create(this, R.raw.racesarts);
        SoundYouPassed = MediaPlayer.create(this, R.raw.youpassed);
        SoundSomeOnePassedYou = MediaPlayer.create(this, R.raw.someonepassedyou);


        tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {

            @Override
            public void onInit(int status) {
                // TODO Auto-generated method stub
                if (status == TextToSpeech.SUCCESS) {
                    //tts.setSpeechRate(f);
                    //ConvertTextToSpeech("race is starting in: ");
                    int result = tts.setLanguage(Locale.UK);
                    tts.setSpeechRate(0.9f);

                    if (result == TextToSpeech.LANG_MISSING_DATA ||
                            result == TextToSpeech.LANG_NOT_SUPPORTED) {
                    }
                } else {
                }
            }
        });
        SoundRaceStarts.start();
        //countdownTimer

        new CountDownTimer(10000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                alertDialog.setTitle("Race starting in " + (String.valueOf((int) (millisUntilFinished / 1000))) + " seconds");
                ConvertTextToSpeech(String.format("%d", millisUntilFinished / 1000));
            }

            @Override
            public void onFinish() {
                alertDialog.dismiss();
                startRace();
            }
        }.start();


        myStats = initMyStats();
        RACE_DISTANCE = Double.valueOf(race.getString("Distance"));
        distanceTextView.setText(String.valueOf(RACE_DISTANCE));

        finishedIntent = new Intent(this, RaceFinished.class);

        //Init Tabs
        final TabHost tabs = (TabHost) findViewById(R.id.tabhost);
        tabs.setup();
        TabHost.TabSpec spec = tabs.newTabSpec("mitab1");
        spec.setContent(R.id.tab1);

        final TabHost.TabSpec spec2 = tabs.newTabSpec("mitab2");
        spec2.setContent(R.id.tab2);

        spec.setIndicator("My Stats", getResources().getDrawable(R.drawable.abc_btn_check_material));
        spec2.setIndicator("Positions", getResources().getDrawable(R.drawable.abc_btn_check_material));

        tabs.addTab(spec);
        tabs.addTab(spec2);

        tabs.setCurrentTab(0);
        tabs.setOnTabChangedListener(new AnimatedTabHostListener(tabs));
        TextView tv = (TextView) tabs.getTabWidget().getChildAt(0).findViewById(android.R.id.title); //Unselected Tabs
        tv.setTextColor(Color.parseColor("#ffffff"));
        tv = (TextView) tabs.getTabWidget().getChildAt(1).findViewById(android.R.id.title); //Unselected Tabs

        tv.setTextColor(Color.parseColor("#ffffff"));

        LinearLayout container = (LinearLayout) findViewById(R.id.container);
        container.setOnTouchListener(new OnSwipeTouchListener(getApplicationContext()) {


            public void onSwipeRight() {
                if (currentTab == 1) {
                    tabs.setCurrentTab(0);
                    currentTab = 0;
                }
            }

            public void onSwipeLeft() {
                if (currentTab == 0) {
                    tabs.setCurrentTab(1);
                    currentTab = 1;
                }
            }

            public boolean onTouch(View v, MotionEvent event) {
                return gestureDetector.onTouchEvent(event);
            }
        });
        //Update rival stats every 2 sec
        raceUpdateHandler = new Handler();
        updateChecker = new UpdateRunnable();
        mJSONAdapter = new JSONAdapterStatsList(this, getLayoutInflater());
        if (mJSONAdapter != null) {

            racesListView = (ListView) findViewById(R.id.listView);
            racesListView.setAdapter(mJSONAdapter);
            racesListView.setOnItemClickListener(this);

        }


        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(final Location location) {
                if (raceStarted == 1) {
                    //Handle the new location
                    runLocationManager.onLocationChangedAsync(location);
                    //Get my statistics about the race until now
                    TripStatistics statistics = runLocationManager.getTripStatistics();
                    //update myStats
                    myStats.ActualDistance = statistics.getTotalDistance() / 1000;
                    myStats.Speed = runLocationManager.getSmoothedSpeed() * KM;
                    //Update GUI elements with updated stats
                    updateGui(statistics, location);
                }
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {
                Toast.makeText(getApplicationContext(), "No GPS connection", Toast.LENGTH_LONG);


            }
        };
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
    }

    /* Updates all of the GUI views with the TripStatistics*/
    private void updateGui(TripStatistics tripStatistics, Location location) {
        if (RACE_DISTANCE - tripStatistics.getTotalDistance() / 1000 >= 0) {
            distanceTextView.setText((String.format("%.2f", (RACE_DISTANCE - tripStatistics.getTotalDistance() / 1000))));
        } else {
            distanceTextView.setText((String.format("%.2f", 0.000f)));

        }
        avgSpeedTextView.setText((String.format("%.1f", tripStatistics.getAverageSpeed() * KM)));
        // minKmTextView.setText((String.format("%.2f",((tripStatistics.getTotalDistance() / (System.currentTimeMillis() - tripStatistics.getStartTime()))))));//tripStatistics.getTotalDistance()));
        speedTextView.setText((String.format("%.1f", (runLocationManager.getSmoothedSpeed() * KM))));
        calorieTextView.setText((String.format("%.0f", (tripStatistics.getCalorie()))));
        distanceFromWinnerTextView.setText((String.format("%.2f", (distanceFromWinner))));
    }

    /* Starts the race for the user*/
    public void startRace() {
        if (multiUserMode)
            ConvertTextToSpeech("Good Luck, may the best man win");
        else
            ConvertTextToSpeech("Good Luck, single user mode");

        startRepeatingTask();
        chronometer.setBase(SystemClock.elapsedRealtime());
        chronometer.start();
        raceStarted = 1;
        //ConvertTextToSpeech("Started Race");
    }

    /* Starts a repeating task which updates the server with the client's location, and gets other
    users progress from  the server*/
    void startRepeatingTask() {
        updateChecker.run();
    }

    void stopRepeatingTask() {
        raceUpdateHandler.removeCallbacks(updateChecker);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

    /*Updates the server*/
    private void postToServer() {
        TripStatistics statistics = runLocationManager.getTripStatistics();
        //Build json object to send to server
        params = new RequestParams();
        params.put("key", String.valueOf(myStats.Key));
        params.put("raceID", String.valueOf(myStats.Race));
        params.put("racer", String.valueOf(myStats.Racer));
        params.put("speed", String.valueOf(statistics.getAverageSpeed() * KM));
        params.put("actualdistance", String.valueOf(myStats.ActualDistance));
        params.put("status", "run");

        //Send json to server
        client.post(SERVER_URL, params, updateStatsResponseHandler);

    }

    private void ConvertTextToSpeech(String str) {
        // TODO Auto-generated method stub

        if (str == null || "".equals(str)) {
            str = "Content not available";
            tts.speak(str, TextToSpeech.QUEUE_FLUSH, null);
        } else
            tts.speak(str, TextToSpeech.QUEUE_FLUSH, null);
    }

    /* Finishes the race for the client*/
    public void giveUp(View view) {
        locationManager.removeUpdates(locationListener);
        stopRepeatingTask();
        TripStatistics statistics = runLocationManager.getTripStatistics();
        finishedIntent.putExtra("user", getIntent().getStringExtra("user"));

        finishedIntent.putExtra("raceID", String.valueOf(myStats.Race));
        finishedIntent.putExtra("time", String.valueOf((SystemClock.elapsedRealtime() - chronometer.getBase()) / 1000));
        finishedIntent.putExtra("averageSpeed", String.valueOf(statistics.getAverageSpeed() * KM));
        finishedIntent.putExtra("participantsNumber", String.valueOf(NUM_OF_PARTICIPANTS));
        finishedIntent.putExtra("distance", String.valueOf(myStats.ActualDistance));
        finishedIntent.putExtra("calories", String.valueOf(runLocationManager.getTripStatistics().getCalorie()));
        finishedIntent.putExtra("finishedAllRace", "0");
        finishedIntent.putExtra("Estimated", getIntent().getStringExtra("Estimated"));


        params2 = new RequestParams();
        params2.put("key", String.valueOf(myStats.Key));
        params2.put("raceID", String.valueOf(myStats.Race));
        params2.put("racer", String.valueOf(myStats.Racer));
        params2.put("speed", String.valueOf(statistics.getAverageSpeed() * KM));
        params2.put("actualdistance", String.valueOf(myStats.ActualDistance));
        params2.put("status", "gaveup");
        params2.put("finishedPosition", String.valueOf(myPosition + 1));
        params2.put("time", String.valueOf((SystemClock.elapsedRealtime() - chronometer.getBase()) / 1000));
        params2.put("gaveup", "1");

        //Send json to server
        client.post(SERVER_URL, params2, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(JSONArray jsonArray) {

                try {
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject runner = jsonArray.getJSONObject(i);
                        long Key = Long.valueOf(runner.get("key").toString());

                        if (Key == myStats.Key) {


                            finishedIntent.putExtra("position", runner.getString("FinishedPosition"));
                            startActivity(finishedIntent);
                            finish();

                        }
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Error getting data from server", Toast.LENGTH_LONG);
                    finishedIntent.putExtra("position", String.valueOf(myRealPos));
                    startActivity(finishedIntent);
                    finish();
                }
            }

            @Override
            public void onFailure(Throwable e, JSONObject errorResponse) {
                Toast.makeText(getApplicationContext(), "Error getting data from server", Toast.LENGTH_LONG);
                finishedIntent.putExtra("position", String.valueOf(myRealPos));
                startActivity(finishedIntent);
                finish();

            }
        });


    }

    /* Init the clients CurrentStats instance */
    public CurrentStats initMyStats() {
        final CurrentStats newStats = new CurrentStats();
        SharedPreferences prefs = getSharedPreferences("MyPrefsFile", Context.MODE_PRIVATE);
        newStats.Racer = Long.valueOf(prefs.getString("userID", ""));
        newStats.Race = Long.valueOf(race.getString("Key"));
        newStats.ActualDistance = 0.0;
        newStats.Speed = 0.0;

        distanceFreq = Double.valueOf(prefs.getString("Settings/distanceFreq", ""));
        timeFreq = Double.valueOf(prefs.getString("Settings/timeFreq", ""));
        informationIndex = Integer.valueOf(prefs.getString("Settings/informationIndex", ""));
        alertsOnTouch = Integer.valueOf(prefs.getString("Settings/onTouchAlerts", "1")) == 1 ? true : false;


        client.get(SERVER_URL_CREATESTATS + "?raceID=" + String.valueOf(newStats.Race) + "&" + "racerID=" + String.valueOf(newStats.Racer) + "&" + "speed=0.0&actualDistance=0.0",
                new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(JSONObject jsonObject) {
                        try {
                            newStats.Key = Long.valueOf(jsonObject.get("currentStat").toString());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Throwable throwable, JSONObject error) {
                        Toast.makeText(getApplicationContext(), "Failed to Start race: Cannot init connection to server", Toast.LENGTH_LONG);

                    }
                });

        return newStats;
    }

    public String distanceFloatToString(float dist) {
        String res;
        if (dist < 1) {
            int temp = (int) (dist * 100); //meters
            return String.valueOf(temp * 10) + " meters";
        } else {
            return String.format("%.1f", dist) + " kilometers";
        }
    }

    @Override
    public void onBackPressed() {

    }

    public void onTouchAlertsLiveRace(View v) {
        long timePassed;
        TripStatistics statistics;
        if (alertsOnTouch) {
            statistics = runLocationManager.getTripStatistics();
            float totalDist = (float) statistics.getTotalDistance();
            totalDist = (float) (totalDist / 1000);
            String totalDistStr = distanceFloatToString(totalDist);
            timePassed = SystemClock.elapsedRealtime() - chronometer.getBase();
            String positionSpeech = String.valueOf(myPosition + 1);
            String timePassedSpeech = String.valueOf(timePassed / 1000) + " seconds ";
            String timeMinutes = "";
            String timeSeconds = "";

            if ((timePassed / 1000) > 60) {
                timeMinutes = String.valueOf((int) (timePassed / 1000) / 60) + " minutes  ";
                if (((timePassed) % 60) > 0) {
                    timeSeconds = " and " + String.valueOf((int) ((int) (timePassed / 1000) % 60)) + " seconds ";
                }
                timePassedSpeech = timeMinutes + timeSeconds;
            }
            String lastNotify = "";
            if (myPosition + 1 == NUM_OF_PARTICIPANTS && multiUserMode) {
                lastNotify = ". you are last,   hurry up.";
            }
            if (myPosition + 1 == 1 && multiUserMode)
                positionSpeech = " you are:  First place, Keep it going  ";
            else if (myPosition + 1 == 2)
                positionSpeech = " you are:  Second place   ";
            else if (myPosition + 1 == 3)
                positionSpeech = " you are:  Third place  ";
            else if (myPosition + 1 == 4)
                positionSpeech = " you are:  Fourth place   ";
            else if (myPosition + 1 == 5)
                positionSpeech = " you are:  Fifth place   ";
            else
                positionSpeech = " position is " + String.valueOf(myPosition + 1);

            if (!multiUserMode) {
                positionSpeech = "";
            }

            String additionalInfo = "";
            if (informationIndex == 2) {
                String avgSpeed = String.format("%.0f ", (statistics.getAverageSpeed() * KM));
                String caloriesBurned = String.format("%.0f", (statistics.getCalorie()));
                String distanceRemains = distanceFloatToString((float) (RACE_DISTANCE - statistics.getTotalDistance() / 1000));//String.format("%.1f .",(RACE_DISTANCE - statistics.getTotalDistance() / 1000));

                additionalInfo = ". average speed.     " + avgSpeed + ".    KPH.       " + " distance remains. " + distanceRemains + ". " + " you burned " + caloriesBurned + " calories.";
            }
            if (informationIndex == 2 && myPosition != 0) {
                String distanceFromWinnerSpeech = distanceFloatToString((float) distanceFromWinner);//String.format("%.2f",distanceFromWinner);
                additionalInfo += " you are " + distanceFromWinnerSpeech + " away from first place.";
            }
            ConvertTextToSpeech(timePassedSpeech + " passed " + " you ran:  " + totalDistStr + positionSpeech + lastNotify + additionalInfo);
        }
    }

    class UpdateRunnable implements java.lang.Runnable {
        @Override
        public void run() {
            //updateRaceStats(); //this function can change value of mInterval.
            postToServer();
            raceUpdateHandler.postDelayed(this, getUpdatesInterval);

        }


    }

    /* A class that handles the servers respons */
    class UpdateStatsResponseHandler extends JsonHttpResponseHandler {

        @Override
        public void onSuccess(JSONArray jsonArray) {
            mJSONAdapter.updateData(jsonArray);
            final List<CurrentStats> statsList = new ArrayList<CurrentStats>();
            numOfParticipants.setText("/" + String.valueOf(jsonArray.length()));
            //updatePositions(jsonArray);
            if (jsonArray != null && jsonArray.length() > 0) {
                JSONObject firstRunner;
                try {
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject runner = jsonArray.getJSONObject(i);
                        long Key = Long.valueOf(runner.get("key").toString());
                        long Race = Long.valueOf(runner.get("race").toString());
                        long Racer = Long.valueOf(runner.get("racer").toString());
                        float Speed = Float.valueOf(runner.get("speed").toString());
                        float ActualDistance = Float.valueOf(runner.get("actualdistance").toString());
                        //int FinishedPosition = Integer.valueOf(runner.get("FinishedPosition").toString());
                        CurrentStats cur = new CurrentStats(Key, Race, Racer, Speed, ActualDistance);
                        statsList.add(cur);
                    }
                    NUM_OF_PARTICIPANTS = statsList.size();
                    //   Collections.sort(statsList);
                    myPosition = 0;
                    myRealPos = 0;


                    TripStatistics statistics = runLocationManager.getTripStatistics();

                    for (int i = 0; i < statsList.size(); i++) {
                        if (statsList.get(i).Key == myStats.Key) { //how to check my key?!?
                            myPosition = i;
                            if (myPosition == 0) {
                                progressLayout.setBackgroundColor(Color.parseColor("#669900"));
                            } else if (myPosition < statsList.size() - 1) {
                                progressLayout.setBackgroundColor(Color.parseColor("#FF8800"));
                            } else {
                                progressLayout.setBackgroundColor(Color.parseColor("#CC0000"));
                            }
                            distanceFromWinner = statsList.get(0).ActualDistance - statsList.get(i).ActualDistance;
                            positionTextView.setText(String.valueOf(myPosition + 1));

                            if (statsList.get(i).ActualDistance > RACE_DISTANCE) {
                                // put.Race.winner........
                                locationManager.removeUpdates(locationListener);
                                stopRepeatingTask();
                                finishedIntent.putExtra("user", getIntent().getStringExtra("user"));
                                finishedIntent.putExtra("raceID", String.valueOf(myStats.Race));
                                //finishedIntent.putExtra("position",String.valueOf(myRealPos));
                                finishedIntent.putExtra("time", String.valueOf((SystemClock.elapsedRealtime() - chronometer.getBase()) / 1000));
                                finishedIntent.putExtra("averageSpeed", String.valueOf(statistics.getAverageSpeed() * KM));
                                finishedIntent.putExtra("participantsNumber", String.valueOf(jsonArray.length()));
                                finishedIntent.putExtra("distance", String.valueOf(RACE_DISTANCE));
                                finishedIntent.putExtra("calories", String.valueOf(runLocationManager.getTripStatistics().getCalorie()));
                                finishedIntent.putExtra("finishedAllRace", "1");
                                finishedIntent.putExtra("Estimated", getIntent().getStringExtra("Estimated"));
                                tts.stop();
                                tts.shutdown();


                                params2 = new RequestParams();
                                params2.put("time", String.valueOf((SystemClock.elapsedRealtime() - chronometer.getBase()) / 1000));
                                params2.put("key", String.valueOf(myStats.Key));
                                params2.put("raceID", String.valueOf(myStats.Race));
                                params2.put("racer", String.valueOf(myStats.Racer));
                                params2.put("speed", String.valueOf(statistics.getAverageSpeed() * KM));
                                params2.put("actualdistance", String.valueOf(myStats.ActualDistance));
                                params2.put("status", "finished");
                                params2.put("finishedPosition", String.valueOf(myPosition + 1));
                                params2.put("gaveup", "0");


                                //Send json to server
                                client.post(SERVER_URL, params2, new JsonHttpResponseHandler() {
                                    @Override
                                    public void onSuccess(JSONArray jsonArray) {
                                        try {
                                            for (int i = 0; i < jsonArray.length(); i++) {
                                                JSONObject runner = jsonArray.getJSONObject(i);
                                                long Key = Long.valueOf(runner.get("key").toString());
                                                if (Key == myStats.Key) {
                                                    String finishedPos = runner.getString("FinishedPosition");
                                                    if (finishedPos == null) {


                                                    } else {

                                                        finishedIntent.putExtra("position", finishedPos);
                                                        startActivity(finishedIntent);
                                                        finish();
                                                    }


                                                }
                                            }


                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                            Toast.makeText(getApplicationContext(), "Error getting data from server", Toast.LENGTH_LONG);
                                            finishedIntent.putExtra("position", String.valueOf(myRealPos));
                                            startActivity(finishedIntent);
                                            finish();
                                        }
                                    }

                                    @Override
                                    public void onFailure(Throwable e, JSONObject errorResponse) {
                                        Toast.makeText(getApplicationContext(), "Error getting data from server", Toast.LENGTH_LONG);
                                        finishedIntent.putExtra("position", String.valueOf(myRealPos));
                                        startActivity(finishedIntent);
                                        finish();

                                    }
                                });


                            }

                            elapsedMillis = SystemClock.elapsedRealtime() - chronometer.getBase();
                            if (informationIndex != 0 && multiUserMode) {
                                if (myPrevPsotion < myPosition && elapsedMillis > 8000) {
                                    SoundSomeOnePassedYou.start();
                                    ConvertTextToSpeech("watch out! someone passed you");
                                }
                                if (myPrevPsotion > myPosition && elapsedMillis > 8000) {
                                    SoundYouPassed.start();
                                    ConvertTextToSpeech("very good! you passed someone");
                                }
                            }
                            myPrevPsotion = myPosition;


                            String positionSpeech = String.valueOf(myPosition + 1);
                            String timePassedSpeech = String.valueOf(elapsedMillis / 1000);
                            String timeMinutes = "";
                            String timeSeconds = "";
                            //speech after XXX time
                            if (informationIndex != 0 && timeFreq != -1) {
                                if ((elapsedMillis / 1000) > timeFreq * timeCnt) {
                                    timePassedSpeech = String.valueOf((int) (timeFreq * timeCnt)) + " seconds ";
                                    if ((elapsedMillis / 1000) > 60) {
                                        timeMinutes = String.valueOf((int) ((timeFreq * timeCnt) / 60)) + " minutes  ";
                                        if (((timeFreq * timeCnt) % 60) > 0)
                                            timeSeconds = " and " + String.valueOf((int) ((timeFreq * timeCnt) % 60)) + " seconds ";
                                        timePassedSpeech = timeMinutes + timeSeconds;
                                    }

                                    float totalDist = (float) statistics.getTotalDistance();
                                    totalDist = (float) (totalDist / 1000);
                                    String totalDistStr = distanceFloatToString(totalDist);

                                    String lastNotify = "";
                                    if (myPosition + 1 == NUM_OF_PARTICIPANTS && multiUserMode) {
                                        lastNotify = ". you are last,   hurry up.";
                                    }
                                    if (myPosition + 1 == 1 && multiUserMode)
                                        positionSpeech = "  First place, Keep it going  ";
                                    else if (myPosition + 1 == 2)
                                        positionSpeech = "  Second place   ";
                                    else if (myPosition + 1 == 3)
                                        positionSpeech = "  Third place  ";
                                    else if (myPosition + 1 == 4)
                                        positionSpeech = "  Fourth place   ";
                                    else if (myPosition + 1 == 5)
                                        positionSpeech = "  Fifth place   ";
                                    else
                                        positionSpeech = " position is " + String.valueOf(myPosition + 1);

                                    if (!multiUserMode) {
                                        positionSpeech = "";
                                    }

                                    String additionalInfo = "";
                                    if (informationIndex == 2) {
                                        String avgSpeed = String.format("%.0f ", (statistics.getAverageSpeed() * KM));
                                        String caloriesBurned = String.format("%.0f", (statistics.getCalorie()));
                                        String distanceRemains = distanceFloatToString((float) (RACE_DISTANCE - statistics.getTotalDistance() / 1000));//String.format("%.1f .",(RACE_DISTANCE - statistics.getTotalDistance() / 1000));

                                        additionalInfo = ". average speed.     " + avgSpeed + ".    KPH.       " + " distance remains. " + distanceRemains + ". " + " you burned " + caloriesBurned + " calories.";
                                    }
                                    if (informationIndex == 2 && i != 0) {

                                        String distanceFromWinnerSpeech = distanceFloatToString((float) distanceFromWinner);//String.format("%.2f",distanceFromWinner);
                                        additionalInfo += " you are " + distanceFromWinnerSpeech + " away from first place.";
                                    }
                                    ConvertTextToSpeech(timePassedSpeech + " passed  " + " you ran:  " + totalDistStr + positionSpeech + lastNotify + additionalInfo);


                                    timeCnt++;
                                }
                                //speech after XXX distance
                                if ((statsList.get(i).ActualDistance > (distanceFreq * distanceCnt))) {
                                    if (informationIndex != 0 && distanceFreq != -1) {
                                        String lastNotify = "";
                                        if (myPosition + 1 == NUM_OF_PARTICIPANTS && multiUserMode) {
                                            lastNotify = ". you are last,   hurry up.";
                                        }
                                        if (myPosition + 1 == 1 && multiUserMode)
                                            positionSpeech = "  First place, Keep it going  ";
                                        else if (myPosition + 1 == 2)
                                            positionSpeech = "  Second place   ";
                                        else if (myPosition + 1 == 3)
                                            positionSpeech = "  Third place  ";
                                        else if (myPosition + 1 == 4)
                                            positionSpeech = "  Fourth place   ";
                                        else if (myPosition + 1 == 5)
                                            positionSpeech = "  Fifth place   ";
                                        else
                                            positionSpeech = "position is " + String.valueOf(myPosition + 1);

                                        if (!multiUserMode) {
                                            positionSpeech = "";
                                        }
                                        if (myPosition + 1 == NUM_OF_PARTICIPANTS && multiUserMode) {
                                            lastNotify = "you are last    hurry up ";
                                        }

                                        String additionalInfo = "";
                                        if (informationIndex == 2) {
                                            String avgSpeed = String.format("%.0f  ", (statistics.getAverageSpeed() * KM));
                                            String caloriesBurned = String.format("%.0f", (statistics.getCalorie()));
                                            String distanceRemains = distanceFloatToString((float) (RACE_DISTANCE - statistics.getTotalDistance() / 1000));

                                            additionalInfo = " average speed is    " + avgSpeed + "     KPH.    " + " distance to go " + distanceRemains + ". " + " you burned " + caloriesBurned + " calories.";
                                        }

                                        if (informationIndex == 2) {
                                            if (i != 0) {
                                                String distanceFromWinnerSpeech = distanceFloatToString((float) (distanceFromWinner));
                                                additionalInfo += " you are " + distanceFromWinnerSpeech + "  away from first place.";
                                            }
                                        }
                                        ConvertTextToSpeech(distanceFloatToString((float) (distanceFreq * distanceCnt)) + " passed " + positionSpeech + lastNotify + additionalInfo);

                                        distanceCnt++;
                                    }
                                }
                            }
                            myRealPos = myPosition;
                        }
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }

        }

        @Override
        public void onFailure(int statusCode, Throwable throwable, JSONObject error) {
        }


    }

}

